package com.pfizer.XmlContentHandler;

import static com.pfizer.Entity.UserInfo.USEREMAILSTRING;
import static com.pfizer.Entity.UserInfo.USERIDSTRING;
import static com.pfizer.Entity.UserInfo.USERINFOSTRING;
import static com.pfizer.Entity.UserInfo.USERNAMESTRING;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.pfizer.Entity.UserInfo;
/**
 * UserInfoContentHandler--<b>解析用戶XML數據</b>
 * 本類用於完成解析XML信息，將解析后的XML放於list中供外部訪問
 * @author krui
 * @version 1.0 2011/11/21
 */
public class UserInfoContentHandler extends DefaultHandler {
	private List<UserInfo> userinfos;
	
	private UserInfo userinfo;
	private StringBuilder sb = new StringBuilder();

	/**
	 * 解析XML數據放于List中，此方法用於外部獲得解析后的數據
	 * 
	 * @return List<UserInfo>
	 */
	public List<UserInfo> getUserInfos() {
		return userinfos;
	}
	/**
	 * 在根標籤開始時就實例化list用於存放每組數據
	 */

	@Override
	public void startDocument() throws SAXException {
		userinfos = new ArrayList<UserInfo>();
	}


	/**
	 * 開始解析數據，將得到的數據放於javabean
	 * 
	 */
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);
		if(ch[0]=='\n'&&length==1)
		{
			return;
		}
		String sTmp = new String(ch, start, length);
		sTmp=sTmp.trim();
		if(sTmp.length()==0)
		{
			return;
		}
		// (2)不管在startElement到endElement的过程中，执行了多少次characters，
		// 都会将内容添加到StringBuilder中，不会丢失内容
		sb.append(sTmp);
	}
	/**
	 * 在一個tag開始時實例化組對象，
	 */
	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {

		if (USERINFOSTRING.equals(localName)) {

			userinfo = new UserInfo();
		} 
	}
	/**
	 * 在一個tag結束后將本組數據放於list
	 */
	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		if(USERINFOSTRING.equals(localName)&&userinfo!=null)
		{
			userinfos.add(userinfo);
			userinfo = null;
		}
		else
		{
			if (userinfo != null) {
				String valueString = sb.toString();
				if(USERIDSTRING.equals(localName))
				{
					userinfo.setUserID(valueString);
				}
				else if (USERNAMESTRING.equals(localName)) 
				{
					userinfo.setUserName(valueString);
				} 
				else if (USEREMAILSTRING.equals(localName)) 
				{
					userinfo.setUserEmail(valueString);
				} 
			}
		}
		sb.delete( 0, sb.length());
	}
}
